package com.xca.znb.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.xca.znb.R;
import com.xca.znb.contact.PersonalCenterContact;
import com.xca.znb.model.impl.PersonalCenterImpl;
import com.xca.znb.presenter.PersonalCenterPresenter;
import com.google.android.material.bottomsheet.BottomSheetDialog;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class PersonalCenter extends AppCompatActivity implements PersonalCenterContact {


    private static final int PICK_IMAGE_REQUEST = 1;
    private BottomSheetDialog bottomSheetDialog ;
    private ImageButton BackBtn ;
    private ImageView ShowConcern ;
    private LinearLayout EditConcern , EditUserName , EditAge , EditLocal ;
    private TextView ShowName , ShowPhone , ShowAge , ShowLocal ;

    private PersonalCenterPresenter personalCenterPresenter ;
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.personal_center);
        BackBtn = findViewById(R.id.personal_center_back_btn);
        EditConcern = findViewById(R.id.edit_concern_btn);
        EditUserName = findViewById(R.id.edit_userName) ;
        EditAge = findViewById(R.id.edit_userAge) ;
        EditLocal = findViewById(R.id.edit_userLocal) ;
        ShowName = findViewById(R.id.personal_center_show_userName) ;
        ShowPhone = findViewById(R.id.personal_center_show_phone) ;
        ShowAge = findViewById(R.id.personal_center_show_age) ;
        ShowLocal = findViewById(R.id.personal_center_show_local);
        ShowConcern = findViewById(R.id.edit_concern_img) ;

        //设置头像
        EditConcern.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
            }
        });


        BackBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        EditUserName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showBottomSheetUpdateName();
            }
        });
        EditAge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showBottomSheetUpdateAge();
            }
        });
        EditLocal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showBottomSheetUpdateLocal();
            }
        });


        PersonalCenterImpl personalCenter = new PersonalCenterImpl(this);
        personalCenterPresenter = new PersonalCenterPresenter(this,personalCenter);
        SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
        String phone = sharedPreferences.getString("phone" , "");
        ShowPhone.setText(phone);
        personalCenterPresenter.showMessage(phone);
    }

    //获取图片路径
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri selectedImageUri = data.getData();
            String imagePath = saveImageToAppFolder(selectedImageUri);

            SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
            String phone = sharedPreferences.getString("phone" , "");
            personalCenterPresenter.updateAvatar(phone,imagePath);
            Glide.with(this)
                    .load(imagePath)
                    .into(ShowConcern);
        }
    }

    //图片保存到本地
    private String saveImageToAppFolder(Uri imageUri) {
        String savedImagePath = null;

        if (imageUri == null || imageUri.toString().isEmpty()) {
            Log.e("ImageSave", "Invalid image Uri provided");
            return null;
        }

        try {
            File dir_news = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
            if (dir_news == null) {
                Log.e("ImageSave", "Failed to get app's private directory");
                return null;
            }

            if (!dir_news.exists() && !dir_news.mkdirs()) {
                Log.e("ImageSave", "Failed to create directories");
                return null;
            }

            // 新增逻辑：确保文件名唯一
            String imageNameBase = "image_";
            String imageNameExtension = ".jpg";
            File file;
            int counter = 0;
            do {
                String imageName = imageNameBase + System.currentTimeMillis() + (counter > 0 ? "_" + counter : "") + imageNameExtension;
                file = new File(dir_news, imageName);
                counter++;
            } while (file.exists());

            try (InputStream inputStream = getContentResolver().openInputStream(imageUri);
                 FileOutputStream outputStream = new FileOutputStream(file)) {

                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                savedImagePath = file.getAbsolutePath();
                Log.d("ImageSave", "Image saved successfully at: " + savedImagePath);
            }
        } catch (SecurityException se) {
            Log.e("ImageSave", "Security exception when accessing storage", se);
        } catch (FileNotFoundException fnfe) {
            Log.e("ImageSave", "Image file not found", fnfe);
        } catch (IOException ioe) {
            Log.e("ImageSave", "Error occurred during image saving", ioe);
        }

        return savedImagePath;
    }


    // 通过Uri获取图片路径
    private String getPathFromUri(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null) {
            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            String path = cursor.getString(columnIndex);
            cursor.close();
            return path;
        }
        return uri.getPath(); // 如果获取不到，则直接返回Uri的路径

    }



    private void showBottomSheetUpdateName(){
        bottomSheetDialog = new BottomSheetDialog(PersonalCenter.this);
        bottomSheetDialog.setContentView(R.layout.update_user_name);
        EditText UpdateName = bottomSheetDialog.findViewById(R.id.update_input_name);
        ImageButton Cancel = bottomSheetDialog.findViewById(R.id.update_name_cancel) ;
        Button Save = bottomSheetDialog.findViewById(R.id.save_new_name_btn) ;

        Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog.dismiss();
            }
        });
        Save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
                String phone = sharedPreferences.getString("phone" , "");
                //获取输入的信息
                String newName = UpdateName.getText().toString() ;
                //直接展示
                ShowName.setText(newName);
                personalCenterPresenter.updateName(phone , newName);
                Toast.makeText(PersonalCenter.this, "信息修改为：" +newName, Toast.LENGTH_SHORT).show();
                bottomSheetDialog.dismiss();
            }
        });
        bottomSheetDialog.show();
    }
    private void showBottomSheetUpdateAge(){
        bottomSheetDialog = new BottomSheetDialog(PersonalCenter.this);
        bottomSheetDialog.setContentView(R.layout.update_user_age);
        EditText UpdateAge = bottomSheetDialog.findViewById(R.id.update_input_age);
        ImageButton Cancel = bottomSheetDialog.findViewById(R.id.update_age_cancel) ;
        Button Save = bottomSheetDialog.findViewById(R.id.save_new_age_btn) ;

        Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog.dismiss();
            }
        });
        Save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
                String phone = sharedPreferences.getString("phone" , "");
                String newAge = UpdateAge.getText().toString();
                ShowAge.setText(newAge);
                personalCenterPresenter.updateAge(phone,newAge);
                Toast.makeText(PersonalCenter.this, "信息修改为：" + newAge, Toast.LENGTH_SHORT).show();
                bottomSheetDialog.dismiss();
            }
        });
        bottomSheetDialog.show();
    }
    private void showBottomSheetUpdateLocal(){
        bottomSheetDialog = new BottomSheetDialog(PersonalCenter.this);
        bottomSheetDialog.setContentView(R.layout.update_user_local);
        EditText UpdateLocal = bottomSheetDialog.findViewById(R.id.update_input_local);
        ImageButton Cancel = bottomSheetDialog.findViewById(R.id.update_local_cancel) ;
        Button Save = bottomSheetDialog.findViewById(R.id.save_new_local_btn) ;

        Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog.dismiss();
            }
        });
        Save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
                String phone = sharedPreferences.getString("phone" , "");
                String newLocal = UpdateLocal.getText().toString() ;
                ShowLocal.setText(newLocal);
                personalCenterPresenter.updateLocal(phone,newLocal);
                Toast.makeText(PersonalCenter.this, "信息修改为：" + newLocal, Toast.LENGTH_SHORT).show();
                bottomSheetDialog.dismiss();
            }
        });
        bottomSheetDialog.show();
    }

    @Override
    public void updateAvatar(String avatarPath) {
       // Toast.makeText(this, avatarPath, Toast.LENGTH_SHORT).show();

        ImageView imageView = findViewById(R.id.edit_concern_img);
        Glide.with(this)
                .load(avatarPath)
                .into(imageView);

    }


    @Override
    public void updateName(String name) {
        ShowName.setText(name);
    }

    @Override
    public void updateAge(String age) {
        ShowAge.setText(age);
    }

    @Override
    public void updateLocal(String local) {
        ShowLocal.setText(local);
    }
}
